﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web.UI;
using System.Threading;

using TimKen.DataEntity;
using TimKen.DataAccess;
using TimKen.BussLogic;
using System.Data.SqlClient;

namespace TimKen.App
{
    /// <summary>
    /// 后台管理页面的基类
    /// </summary>
    public class AdminPage : Page
    {
        /// <summary>
        /// 获取多语言
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetLangString(string key)
        {
            return TimKen.Localization.LocalizationUtility.GetText(key);
        }


        /// <summary>
        /// 语言ID
        /// </summary>
        public int LanguageID 
        {
            get 
            {
                switch(Thread.CurrentThread.CurrentUICulture.ToString())
                {
                    case "zh-CN":return 1; 
                    case "en-US":return 2;
                    default: return 1;
                }
            }
        }


        /// <summary>
        /// 语言条件字符串
        /// </summary>
        public string LanguageWhereStr
        {
            get
            {
                return " LanguageID=" + LanguageID;
            }
        }


        /// <summary>
        /// 上传文件相对路径
        /// </summary>
        public string UploadFilePath
        {
            get
            {
                return "/upload/";
            }
        }

        public const string UploadFilePathForUser = "/upload/user/";
        public const string UploadFilePathForProduct = "/upload/product/";


  
        /// <summary>
        /// 上传文件物理路径
        /// </summary>
        public string PhysicalUploadFilePath 
        {
            get 
            {
                return Server.MapPath(UploadFilePath);
            }
        }


        public string PhysicalUploadFilePathForUser
        {
            get
            {
                return Server.MapPath(UploadFilePathForUser);
            }
        }


        public string PhysicalUploadFilePathForProduct
        {
            get
            {
                return Server.MapPath(UploadFilePathForProduct);
            }
        }


        /// <summary>
        /// 获取Bool值的图片
        /// </summary>
        /// <returns></returns>
        public string GetBoolPic(bool IsTrue)
        {
            string boolImg = "<img src='../../Admin/Images/{0}' title='{1}' alt='{1}'>";
            return IsTrue ? string.Format(boolImg, "yes.gif",GetLangString("Yes")) : string.Format(boolImg, "no.gif",GetLangString("No"));
        }


        /// <summary>
        /// 在前台通过js弹出消息窗口,确定后跳转到主页面
        /// </summary>
        /// <param name="msg">弹出消息</param>
        /// <param name="url">跳转页面url</param>
        protected void Alert(string msg, string url)
        {
            System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "ok", "alert('" + msg + "');window.location='" + url + "';", true);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="fieldType"></param>
        /// <returns></returns>
        public string GetOptionType(string fieldType)
        {
            switch (fieldType)
            {
                case "0": return GetLangString("FieldType_TextBox");
                case "1": return GetLangString("FieldType_TextArea");
                case "2": return GetLangString("FieldType_Select");
                default: return GetLangString("FieldType_TextBox");
            }
        }

        /// <summary>
        /// 在前台通过js弹出消息窗口
        /// </summary>
        /// <param name="msg">弹出消息</param>
        protected void Alert(string msg)
        {
            System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "ok", "<script language='javascript' type='text/javascript'>alert('" + msg + "');</script>", false);
            //ClientScript.RegisterStartupScript(this.GetType(), "ok", "<script>alert(\"" + msg + "\");</script>");
        }

        /// <summary>
        /// 根据品牌ID获取品牌名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetBrandName(object id)
        {
            if (!TypeParse.IsNumeric(id))
                return "";

            int brandId = Convert.ToInt32(id);
         
            string sql = "SELECT  Name FROM  PBrand WHERE BrandID=" + brandId;
           object  brandName =   DbHelperSQL.GetSingle(sql);

           if (brandName == null)
                return "";

           return brandName.ToString();
        }


        /// <summary>
        /// 获取多语言的单位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetUnit(string UnitEn)
        {
            string sql = "SELECT BaseUnitDesc  FROM BaseUnit WHERE BaseUnit='{0}' AND LanguageID={1}";
            sql = string.Format(sql, UnitEn, LanguageID);
            object Unit = DbHelperSQL.GetSingle(sql);

            if (Unit == null)
                return "";

            return Unit.ToString();
        }





        /// <summary>
        /// 根据产品类型ID获取产品类型名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetCategoryName(object id)
        {
            if (!TypeParse.IsNumeric(id))
                return "";

            int categoryId = Convert.ToInt32(id);
            PCategoryManager categoryManager = new PCategoryManager();
            

            PCategory catetory = categoryManager.GetModel(categoryId,(LanguageEnum)LanguageID);

            if (catetory == null)
                return "";
            return catetory.CategoryName;
        }


        /// <summary>
        /// 根据品牌名称获取品牌ID
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public  int  GetBrandID(string name)
        {
            string sql = string.Format("SELECT  BrandID  FROM  PBrand WHERE  Name='{0}'",name);
            object id = DbHelperSQL.GetSingle(sql);
            if (id == null)
                return  0;
            return   Convert.ToInt16(id) ;
        }



        /// <summary>
        /// 根据产品类型名称获取产品类型ID
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public  int GetCategoryID(string name)
        {
            PCategoryManager categoryManager = new PCategoryManager();
            string sql = string.Format("SELECT  CategoryID  FROM  PCategory WHERE LanguageID=2 AND  CategoryName='{0}'", name);
            object  id = DbHelperSQL.GetSingle(sql);
            if (id == null)
                return 0;
            return Convert.ToInt16(id);
        }



        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            //权限控制

            if (Session["Admin"] == null)
                Response.Redirect("/Admin/Login.aspx?reurl="+Request.RawUrl,true);
            if (!CheckAction(ActionCode))
                AuthorityFailed();
               
        }

        /// <summary>
        /// 当前登陆用户名
        /// </summary>
        public string CurrentUserName 
        {
            get { return Session["Admin"] == null ? null : ((UserS)Session["Admin"]).UserName; }
        }

        /// <summary>
        /// 设定权限码
        /// </summary>
        public virtual string ActionCode
        {
            get;
            set;
        }


        /// <summary>
        /// 判断当前用户是否拥有指定的权权限
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public bool CheckAction(string ActionCode)
        {
            if (string.IsNullOrEmpty(ActionCode))
                return true;

         //   UserAccountManager  um = new UserAccountManager();
            UserAccount user = Session["Admin"] as UserAccount;
            if (user == null)
                return false;

            ///如果是系统管理员,则直接返回true
            if (user.RoleID == 0)
                return true;

            if (user == null || string.IsNullOrEmpty(user.ActionList) || (user.RoleID != 0 && user.RoleID != 1))
                return false;


            foreach (string str in user.ActionList.Split(','))
            {
                if (str.Equals(ActionCode))
                    return true;
            }

            return false;

        }

        public bool IsInRoleAdmin() 
        {
            UserAccount user = Session["Admin"] as UserAccount;
            if (user == null)
                return false;

            ///如果是系统管理员,则直接返回true
            if (user.RoleID == 0)
                return true;
            return false;
        }
        /// <summary>
        /// 无权访问
        /// </summary>
        public void AuthorityFailed() 
        {
            Response.Redirect("/admin/NotAuthorized.aspx", true);
        }

        /// <summary>
        /// 通过运输方式ID获取运输方式名称
        /// </summary>
        /// <param name="TransTypeID"></param>
        /// <returns></returns>
        public string GetTransTypeName(int?  TransTypeID) 
        {
            if (!TransTypeID.HasValue)
                return "";
            string sql = "SELECT  TransTypeName  FROM  TransType WHERE TransTypeID={0} AND LanguageID={1}";

            sql = string.Format(sql, TransTypeID.Value, LanguageID);

            object TransTypeName = DbHelperSQL.GetSingle(sql);

            if (TransTypeName == null)
                return "";

            return TransTypeName.ToString();
        }


        public string GetPageResource(string resourceName)
        {
            return _resourceManagerInstance.GetString(resourceName);
        }

        public string GetProductBasePrice(int ProductID)
        {
            ProductManager pm = new ProductManager();
            Product product = pm.GetModel(ProductID);
            string result = "";

            PPrice price = new PPrice();
            string sql = "SELECT Currency,Price  FROM PPrice  WHERE ItemCode='{0}'";
            sql = string.Format(sql, product.ItemCode.Trim());

            SqlDataReader  reader =  DbHelperSQL.ExecuteReader(sql);

            while (reader.Read())
            {
                result += reader[0].ToString() + ":" + reader[1].ToString() + "&nbsp;&nbsp;&nbsp;";
            }
            reader.Close();
            reader.Dispose();

            return result;
        }


       
        System.Resources.ResourceManager _resourceManagerInstance =
              new System.Resources.ResourceManager("TimKen.Web.Admin.Survey.Resources.NSurveyAdmin",
              System.Reflection.Assembly.LoadWithPartialName("TimKen.Web"));

    }
}
